package web.controllers;

import javax.validation.Valid;

import map.beans.EmpResponseBean;
import map.beans.GeneralConfigBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import web.service.interfaces.AdditionalConfigServiceInterface;


@Controller
@RequestMapping("/admin/map")
public class AdditionalConfigController {
	private static Logger LOGGER = LoggerFactory.getLogger(AdditionalConfigController.class);	
	
	@Autowired
	AdditionalConfigServiceInterface addConfigManager;
	
	@RequestMapping(value = "/update/general/config", method = RequestMethod.POST)
	@ResponseBody 
	public EmpResponseBean updateGeneralConfiguration(@Valid @ModelAttribute(value = "generalConfigBean") GeneralConfigBean generalConfigBean, BindingResult result) {		
		EmpResponseBean res = new EmpResponseBean();

		ValidationUtils.rejectIfEmpty(result, "lat", 	"Default Latitude  can NOT be null");
		ValidationUtils.rejectIfEmpty(result, "lon", 	"Default Longitude can NOT be null");
		ValidationUtils.rejectIfEmpty(result, "scale",	"Default Scale can NOT be null");		
		
		if ( !result.hasErrors() ) {
			addConfigManager.update(generalConfigBean);

			res.setStatus("Success");
			res.setResult(generalConfigBean);
		} else {
			res.setStatus("Failed");
			res.setResult(result.getAllErrors());
			LOGGER.warn(res.getStatus());
		}

		return res;
	}
	
	@RequestMapping(value = "/general/config", method = RequestMethod.POST)
	@ResponseBody 
	public EmpResponseBean getGeneralConfiguration() {		
		EmpResponseBean resp = new EmpResponseBean();		

		try {
			resp.setResult(addConfigManager.getDefaultConfig());
			resp.setStatus("Success");
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
			resp.setStatus("Failed");
		}

		return resp;
	}
}
